<?php

declare(strict_types=1);

namespace App\Service\Admin;


use App\Constants\ErrorCode;
use App\Dao\CooperativeDao;
use App\Exception\BusinessException;
use App\Model\Percentage;
use App\Utils\Excel;
use Hyperf\Di\Annotation\Inject;

class PercentageService extends BaseService
{
    /**
     * @Inject()
     * @var CooperativeDao
     */
    protected $cooperativeDao;


    /**
     * @param array $data
     * @return \Psr\Http\Message\ResponseInterface
     * @throws \PhpOffice\PhpSpreadsheet\Writer\Exception
     */
    public function percentageExport(array $data)
    {
        $whereRegion = [];
        if (isset($data['province']) && $data['province'] != '') {
            $whereRegion['province'] = $data['province'];
        }
        if (isset($data['city']) && $data['city'] != '') {
            $whereRegion['city'] = $data['city'];
        }
        $cooperativeIds = $this->cooperativeDao->getCooperativeIdsByRegion($whereRegion);

        $startTime = $data['date'] . ' 00:00:00';
        $endTime = $data['date'] . ' 23:59:59';

        $percentage = Percentage::query()
            ->with('user')
            ->with('cooperative')
            ->whereIn('cooperative_id', $cooperativeIds)
            ->where('created_at', '>=', $startTime)
            ->where('created_at', '<=', $endTime)
            ->get();

        if (count($percentage) == 0) {
            throw new BusinessException(ErrorCode::EXCEL_EXPORT_EMPTY);
        }

        $exportData = [];

        $head = [
            '悬赏主',
            '手机号/账号',
            '时间',
            '提成金额',
            '合作商'
        ];

        foreach ($percentage as $v) {
            /** @var Percentage $value */
            $value = $v;
            array_push(
                $exportData,
                [
                    'nickname' => $value->user->nickname,
                    'phone' => $value->user->phone,
                    'created_at' => $value->created_at,
                    'price' => $value->price,
                    'cooperative' => $value->cooperative->nickname
                ]
            );
        }

        return Excel::export(
            '平台提成流水',
            $exportData,
            $head
        );
    }
}